<template>
  <PageContainer>
    <Header v-model="headerHeight" title="" />
    <view class="container" :style="{ height: `calc(100vh - ${headerHeight}px)` }">
      <view class="top-tips px-16 py-10 fz-14 mb-16">
        <text class="ali-icon mr-8">&#xe699;</text>
        <text>暂未查询到您的报名信息，请使用下列方式签到</text>
      </view>
      <view class="default-color disFlxAC px-16 fz-24 mb-12">
        <text>{{ currentTitle }}</text>
        <view
          v-if="signTypes.length > 1"
          class="disFlxAC br-16 fz-14 px-16 py-6 ml-12 toggle-button"
          @click="handleShowActionSheet"
        >
          <text>切换签到方式</text>
          <text class="ali-icon fz-16 ml-8">&#xe691;</text>
        </view>
      </view>
      <view class="types-view disFlx flex-1" :style="{ marginLeft: getTypesViewMarginLeft }">
        <!-- 手机号码签到 -->
        <view v-if="signTypes.includes(SignTypesEnum.PHONE)" class="types-view__item">
          <!-- <view class="px-16 fz-14 mb-12 des-color">
            <text>输入校验报名预留的手机号</text>
          </view> -->
          <view class="px-16 fz-14 mb-12 des-color">
            <text>如需代他人签到，请输入实际报名人的信息进行签到</text>
          </view>
          <view class="input-view disFlxAC my-40 mx-16 px-16 br-12">
            <view class="fz-14 label-color mr-16">
              <text>手机号</text>
            </view>

            <UniEasyinput
              v-model="inputVal"
              :inputBorder="false"
              :focus="false"
              :placeholder="`输入报名预留的手机号`"
              :placeholderStyle="placeholderStyle"
            />
          </view>
          <view class="px-16">
            <TButton
              text="核验签到"
              type="primary"
              custom-class="h-44 linh-44 br-22 px-16"
              @click="handlePhoneSign"
            />
            <TButton
              v-if="enrollSign"
              text="还未报名？立即报名 >"
              type="none"
              custom-class="br-22"
              :custom-style="{
                color: '#2878FF',
                border: '1px solid #2878FF',
                boxSizing: 'content-box',
                marginTop: '32rpx',
              }"
              @click="toRegistration"
            />
          </view>
        </view>
        <!-- 数字码签到 -->
        <view v-if="signTypes.includes(SignTypesEnum.TICKET_NUMBER)" class="types-view__item">
          <!-- <view class="px-16 fz-14 mb-12 des-color">
            <text>请输入报名后获得的数字码凭证</text>
          </view> -->
          <view class="px-16 fz-14 mb-12 des-color">
            <text>如需代他人签到，请输入实际报名人的信息进行签到</text>
          </view>
          <view class="input-view disFlxAC my-40 mx-16 px-16 br-12">
            <view class="fz-14 label-color mr-16">
              <text>数字码</text>
            </view>

            <UniEasyinput
              v-model="inputVal"
              :inputBorder="false"
              :focus="false"
              :placeholder="`输入获得的凭证数字码`"
              :placeholderStyle="placeholderStyle"
            />
          </view>
          <view class="px-16">
            <TButton
              text="核验签到"
              type="primary"
              custom-class="h-44 linh-44 br-22 px-16"
              @click="handleCodeSign"
            />
            <TButton
              v-if="enrollSign"
              text="还未报名？立即报名 >"
              type="none"
              custom-class="br-22"
              :custom-style="{
                color: '#2878FF',
                border: '1px solid #2878FF',
                boxSizing: 'content-box',
                marginTop: '32rpx',
              }"
              @click="toRegistration"
            />
          </view>
        </view>
        <!-- 二维码签到 -->
        <view v-if="signTypes.includes(SignTypesEnum.TICKET_QRCODE)" class="types-view__item">
          <!-- <view class="px-16 fz-14 mb-12 des-color">
            <text>请从手机相册选择二维码凭证识别签到</text>
          </view> -->
          <view class="px-16 fz-14 mb-12 des-color">
            <text>如需代他人签到，请输入实际报名人的信息进行签到</text>
          </view>

          <view class="px-16 my-40">
            <TButton
              text="去扫一扫签到"
              type="primary"
              custom-class="h-44 linh-44 br-22 px-16"
              @click="handleScanCodeSign"
            />
            <TButton
              v-if="enrollSign"
              text="还未报名？立即报名 >"
              type="none"
              custom-class="br-22"
              :custom-style="{
                color: '#2878FF',
                border: '1px solid #2878FF',
                boxSizing: 'content-box',
                marginTop: '32rpx',
              }"
              @click="toRegistration"
            />
          </view>
        </view>
        <!-- 姓名签到 -->
        <view v-if="signTypes.includes(SignTypesEnum.NAME)" class="types-view__item">
          <!-- <view class="px-16 fz-14 mb-12 des-color">
            <text>请从输入报名时填写的姓名搜索，选中属于您的报名信息进行签到；</text>
          </view> -->
          <view class="px-16 fz-14 mb-12 des-color">
            <text>如需代他人签到，请输入实际报名人的信息进行签到</text>
          </view>
          <view class="input-view disFlxAC my-40 mx-16 px-16 br-12">
            <view class="fz-14 label-color mr-16">
              <text>姓名</text>
            </view>

            <UniEasyinput
              v-model="inputVal"
              :inputBorder="false"
              :focus="false"
              :placeholder="`输入报名预留的姓名`"
              :placeholderStyle="placeholderStyle"
            />
          </view>
          <view class="px-16">
            <TButton
              text="识别签到"
              type="primary"
              custom-class="h-44 linh-44 br-22 px-16"
              @click="handleSearchInfo(SignTypeEnum.MINI_NAME_SIGN_IN)"
            />
            <TButton
              v-if="enrollSign"
              text="还未报名？立即报名 >"
              type="none"
              custom-class="br-22"
              :custom-style="{
                color: '#2878FF',
                border: '1px solid #2878FF',
                boxSizing: 'content-box',
                marginTop: '32rpx',
              }"
              @click="toRegistration"
            />
          </view>
        </view>
        <!-- 单位名称签到 -->
        <view v-if="signTypes.includes(SignTypesEnum.UNIT)" class="types-view__item">
          <!-- <view class="px-16 fz-14 mb-12 des-color">
            <text>请从输入报名时填写的完整单位名称搜索，选中属于您的报名信息进行签到；</text>
          </view> -->
          <view class="px-16 fz-14 mb-12 des-color">
            <text>如需代他人签到，请输入实际报名人的信息进行签到</text>
          </view>
          <view class="input-view disFlxAC my-40 mx-16 px-16 br-12">
            <view class="fz-14 label-color mr-16">
              <text>单位名称</text>
            </view>

            <UniEasyinput
              v-model="inputVal"
              :inputBorder="false"
              :focus="false"
              :placeholder="`输入报名预留的单位名称`"
              :placeholderStyle="placeholderStyle"
            />
          </view>
          <view class="px-16">
            <TButton
              text="识别签到"
              type="primary"
              custom-class="h-44 linh-44 br-22 px-16"
              @click="handleSearchInfo(SignTypeEnum.MINI_UNIT_SIGN_IN)"
            />
            <TButton
              v-if="enrollSign"
              text="还未报名？立即报名 >"
              type="none"
              custom-class="br-22"
              :custom-style="{
                color: '#2878FF',
                border: '1px solid #2878FF',
                boxSizing: 'content-box',
                marginTop: '32rpx',
              }"
              @click="toRegistration"
            />
          </view>
        </view>
      </view>
      <!-- <view v-if="signTypes.length > 1" class="px-16">
        <view class="disFlxAC py-8">
          <view class="h-1 flex-1" style="background-color: #ebedf0"></view>
          <view class="fz-12 mx-8" style="color: #999996">
            <text>其他签到方式</text>
          </view>
          <view class="h-1 flex-1" style="background-color: #ebedf0"></view>
        </view>
        <view class="pt-16 pb-32 disFlxAC" style="justify-content: space-around">
          <template v-for="v in signModeList" :key="v.type">
            <view
              v-if="currentTypes !== v.type && signTypes.includes(v.type)"
              class="disFlxCC"
              @click="handleSignModeToggle(v.type)"
            >
              <text class="ali-icon fz-24 mb-12 type-icon">{{ v.icon }}</text>
              <view class="fz-12" style="color: #999996">
                <text>{{ v.name }}</text>
              </view>
            </view>
          </template>
        </view>
      </view> -->
    </view>
  </PageContainer>

  <ActionSheet v-model="actionSheetVisible" title="切换签到方式" :item-list="signModeList">
    <template v-slot="{ item, index }">
      <view
        v-if="item.show"
        class="disFlxJS px-16 py-12 flex-1"
        @click="handleSignModeToggle(index)"
      >
        <view>
          <view class="fz-16 default-color">{{ item.text }}</view>
          <view class="fz-14" style="color: #999996">{{ item.des }}</view>
        </view>
        <view>
          <text v-if="currentTypes === index + 1" class="ali-icon fz-16" style="color: #2878ff">
            &#xe693;
          </text>
          <text v-else class="ali-icon fz-16" style="color: #969799">&#xe690;</text>
        </view>
      </view>
    </template>
  </ActionSheet>
  <SelectRegistrationInfo ref="selectRegistrationInfoRef" @submit="handleSelectRegistrationInfo" />
</template>

<script lang="ts" setup>
  /* selfRegistration 自主签到 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import UniEasyinput from '@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { onLoad, reLaunch } from '@/router';
  import type { SelfRegistration } from '@/router/types/modules';
  import { SignTypeEnum } from '@/enums/activityStatusEnum';
  import { computed, ref } from 'vue';
  import { SignTypesEnum } from '@/enums/activityStatusEnum';
  import { activityGetSignTypes, activityScanVerification } from '@/api/activity';
  import type {
    ActivityGetSignTypesResult,
    ActivityScanVerificationData,
    ISearchRegisterListResult,
  } from '@/api/activity/types';
  import { Toast } from '@/utils';
  import { useActivityStore } from '@/store/modules/activity';
  import { toActivityRegistration } from '../../utils';
  import SelectRegistrationInfo, {
    type ISelectRegistrationInfoRef,
  } from './components/SelectRegistrationInfo.vue';
  import ActionSheet, { type ActionSheetItem } from '@/components/ActionSheet/index.vue';

  const { getActivityOrderRouteParams } = useActivityStore();
  const signTypes = ref<SignTypesEnum[]>([]);
  const param = ref<SelfRegistration>();
  const currentTypes = ref<SignTypesEnum>();
  const headerHeight = ref<number>(87);
  const placeholderStyle = ref('font-size:28rpx')
  const isLoading = ref(false);
  const enrollSign = ref<ActivityGetSignTypesResult['enrollSign']>();

  const selectRegistrationInfoRef = ref<ISelectRegistrationInfoRef | null>(null);

  const inputVal = ref<string>();

  const actionSheetVisible = ref(false);

  function handleShowActionSheet() {
    actionSheetVisible.value = true;
  }

  const signModeList = ref<ActionSheetItem[]>([]);

  const currentTitle = ref<string>();

  function handleSignModeToggle(index: number) {
    actionSheetVisible.value = false;
    currentTitle.value = signModeList.value[index].text;
    inputVal.value = '';
    currentTypes.value = index + 1;
  }

  onLoad<'selfRegistration'>(async (op) => {
    param.value = op;
    const res = await activityGetSignTypes(op.activityId);
    enrollSign.value = res.enrollSign;
    signTypes.value = res.signTypes
      .split(',')
      .map((item) => Number(item))
      .sort((a, b) => a - b)
      .filter((item) => item !== 1);

    signModeList.value = [
      {
        text: '占位',
        show: false,
      },
      {
        text: '手机号签到',
        show: signTypes.value.includes(SignTypesEnum.PHONE),
        des: '输入报名填写的手机号码匹配签到',
      },
      {
        text: '数字码签到',
        show: signTypes.value.includes(SignTypesEnum.TICKET_NUMBER),
        des: '使用报名成功后获得的数字码凭证签到',
      },
      {
        text: '二维码签到',
        show: signTypes.value.includes(SignTypesEnum.TICKET_QRCODE),
        des: '使用报名成功后获得的二维码凭证签到',
      },
      {
        text: '姓名签到',
        show: signTypes.value.includes(SignTypesEnum.NAME),
        des: '输入报名填写的姓名搜索签到',
      },
      {
        text: '单位名称签到',
        show: signTypes.value.includes(SignTypesEnum.UNIT),
        des: '输入报名填写的单位名称搜索签到',
      },
    ];
    if (signTypes.value.length) {
      currentTypes.value = signTypes.value[0];
      currentTitle.value = signModeList.value[signTypes.value[0] - 1].text;
    }
  });

  const getTypesViewMarginLeft = computed(() => {
    const index = signTypes.value.findIndex((v) => v === currentTypes.value);
    if (index === -1) return 0;
    return `-${index * 100}vw`;
  });

  function handlePhoneSign() {
    if (isLoading.value) return;
    if (!inputVal.value) return Toast('请先填写手机号');
    handleSubmit(
      {
        activityId: param.value?.activityId as number,
        phone: inputVal.value,
      },
      SignTypeEnum.PHONE_SIGN_IN,
    );
  }

  function handleCodeSign() {
    if (isLoading.value) return;
    if (!inputVal.value) return Toast('请先填写数字码');
    handleSubmit(
      {
        activityId: param.value?.activityId as number,
        consumeNo: inputVal.value,
      },
      SignTypeEnum.NUMBER_CODE_SIGN_IN,
    );
  }

  function handleScanCodeSign() {
    if (isLoading.value) return;
    uni.scanCode({
      scanType: ['qrCode'],
      success: ({ result }) => {
        handleSubmit(
          {
            activityId: param.value?.activityId as number,
            consumeNo: result,
          },
          SignTypeEnum.QR_CODE_SIGN_IN,
        );
      },
    });
  }

  const searchInfoSignType = ref<SignTypeEnum>();
  function handleSearchInfo(signType: SignTypeEnum) {
    if (isLoading.value) return;
    if (!inputVal.value) {
      return Toast(`请先填写${signType === SignTypeEnum.MINI_NAME_SIGN_IN ? '姓名' : '单位名称'}`);
    }

    const valKey = signType === SignTypeEnum.MINI_NAME_SIGN_IN ? 'personName' : 'companyName';
    searchInfoSignType.value = signType;
    selectRegistrationInfoRef.value?.show({
      activityId: param.value?.activityId as number,
      [valKey]: inputVal.value,
    });
  }

  function handleSelectRegistrationInfo(data: ISearchRegisterListResult) {
    handleSubmit(
      {
        activityId: param.value?.activityId as number,
        registerId: data.id,
      },
      searchInfoSignType.value!,
    );
  }

  function handleSubmit(data: ActivityScanVerificationData, signType: SignTypeEnum) {
    isLoading.value = true;
    activityScanVerification(data)
      .then((res) => {
        if (res.manualSign) {
          reLaunch({
            name: 'activitySign',
            options: {
              activityId: param.value?.activityId as number,
              activityRegisterId: res.id,
              equipmentNumber: param.value?.equipmentNumber,
              signType,
            },
          });
        } else {
          reLaunch({
            name: 'signInResult',
            options: {
              activityId: param.value?.activityId as number,
              equipmentNumber: param.value?.equipmentNumber as string,
              activityRegisterId: res.id,
              signType,
            },
          });
        }
      })
      .finally(() => (isLoading.value = false));
  }

  function toRegistration() {
    toActivityRegistration({
      data: getActivityOrderRouteParams!,
      shareKey: void 0,
      isVerifyNumber: false,
      routerScene: 'signIn',
      equipmentNumber: param.value?.equipmentNumber,
    });
    // reLaunch({
    //   name: 'activityDetails',
    //   options: {
    //     id: param.value?.activityId as number,
    //   },
    // });
  }
</script>

<style lang="scss" scoped>
  .container {
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .top-tips {
      background-color: #fff4e7;
      color: #e29942;
    }

    .types-view {
      transition: all 0.3s;
      width: 100vw;
      margin-left: 0;
      &__item {
        width: 100vw;
        flex-shrink: 0;
      }
    }

    .des-color {
      color: #969799;
    }

    .label-color {
      color: #646566;
    }

    .input-view {
      background-color: #f7f8fa;
      height: 88rpx;
    }

    .type-icon {
      width: 80rpx;
      height: 80rpx;
      text-align: center;
      line-height: 80rpx;
      background-color: #f2f3f5;
      border-radius: 50%;
    }

    .toggle-button {
      border: 1px solid #2878ff;
      color: #2878ff;
    }
  }
</style>
